package com.kof.picviewer.service;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.kof.picviewer.MainApplication;
import javafx.stage.DirectoryChooser;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

@Service("fileService")
public class FileService {

    /**
     * 当前文件夹
     */
    private String currentFolder;
    public static void main(String[] args) {
        Path rootPath = Paths.get("D:\\workspace\\java\\dist\\pic");
        try {
            JSONObject tree = buildDirectoryTree(rootPath);
            System.out.println(tree);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 选择文件夹
     */

    public void selectFolder() {
        DirectoryChooser fileChooser = new DirectoryChooser();
        fileChooser.setTitle("选择文件夹");
        File file = fileChooser.showDialog(MainApplication.primaryStage);
        currentFolder = file.getAbsolutePath();
    }

    /**
     * 读取文件并将其转换为 Base64 字符串
     *
     * @param filePath 文件路径
     * @return Base64 编码的字符串
     * @throws Exception 如果读取文件或编码过程中发生错误
     */
    public String base64StrFromFile(String filePath) throws Exception {
        // 读取文件内容为字节数组
        byte[] fileContent = Files.readAllBytes(Paths.get(filePath));
        // 将字节数组转换为 Base64 编码的字符串
        String base64String = "data:image/jpeg;base64,"+ Base64.getEncoder().encodeToString(fileContent);
        return base64String;
    }

    /**
     * 获取当前文件夹下的所有文件
     *
     * @return JSONArray 包含所有文件的信息
     * @throws IOException 如果发生文件读取错误
     */
    public JSONArray getFileData() throws IOException {
        String path = currentFolder;
        Path rootPath = Paths.get(currentFolder);
        JSONObject jsonObject = buildDirectoryTree(rootPath);
        return jsonObject.getJSONArray("children");
    }

    /**
     * 构建目录树
     *
     * @param root 目录根路径
     * @return 目录树根节点的 JSON 对象
     * @throws IOException 如果发生文件读取错误
     */
    public static JSONObject buildDirectoryTree(Path root) throws IOException {
        JSONObject rootJson = new JSONObject();
        rootJson.put("name", root.getFileName().toString());
        rootJson.put("path", root.toString());

        List<Path> files = new ArrayList<>();
        List<Path> directories = new ArrayList<>();

        try (DirectoryStream<Path> stream = Files.newDirectoryStream(root)) {
            for (Path entry : stream) {
                if (Files.isDirectory(entry)) {
                    directories.add(entry);
                } else {
                    files.add(entry);
                }
            }
        }

        JSONArray children = new JSONArray();

        for (Path file : files) {
            JSONObject fileJson = new JSONObject();
            fileJson.put("name", file.getFileName().toString());
            fileJson.put("path", file.toString());
            children.add(fileJson);
        }

        for (Path directory : directories) {
            children.add(buildDirectoryTree(directory));
        }

        rootJson.put("children", children);
        return rootJson;
    }


}
